package com.healthcare.client.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 保存session数据
 * @author Dora
 * @date 2019/10/29 19:12
 */
public class SessionUtils {

    /**
     * 获取request
     * @return
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes==null? null : requestAttributes.getRequest();
    }

    /**
     * 获取session
     * @return
     */
    public static HttpSession getSession(){
        return getRequest().getSession(true);
    }

    /**
     * 将数据保存到session
     * @param key
     * @param value
     */
    public static void addSession(String key, Object value){
        getSession().setAttribute(key, value);
    }

    /**
     * 将数据保存到session
     * @param key
     */
    public static Object getSessionAttr(String key){
        return getSession().getAttribute(key);
    }

    /**
     * 获取ip
     * @return
     */
    public static String getIp() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if(servletRequestAttributes!=null){
            HttpServletRequest request = servletRequestAttributes.getRequest();
            return request.getRemoteAddr();
        }
        return "127.0.0.1";
    }

    /**
     * 删除session中的Attribute
     * @param key
     */
    public static void removeSession(String key) {
        getRequest().getSession().removeAttribute(key);
    }
}
